package org.spiderflow.ocr.executor.shape;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderflow.ExpressionEngine;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.spiderflow.ocr.model.Ocr;
import org.spiderflow.ocr.service.OcrService;
import org.spiderflow.ocr.utils.OcrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OcrOperationExecutor implements ShapeExecutor{
	
	public static final String OCR_ID = "ocrId";
	
	public static final String BYTES_OR_URL = "bytesOrUrl";
	
	public static final String VARIABLE_NAME = "variableName";

	private static Logger logger = LoggerFactory.getLogger(OcrOperationExecutor.class);

	@Autowired
	private ExpressionEngine engine;

	@Autowired
	private OcrService ocrService;
	
	@Override
	public String supportShape() {
		return "ocrOperation";
	}
	
	@Override
	public Shape shape() {
		Shape shape = new Shape();
		shape.setImage("");
		shape.setLabel("OCR识别");
		shape.setName("ocrOperation");
		shape.setTitle("OCR识别");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		try {
			int ocrId = NumberUtils.toInt(node.getStringJsonValue(OCR_ID,"0"),0);
			if(ocrId == 0){
				logger.debug("请选择OCR！");
			}else {
				Ocr ocr = ocrService.get(ocrId + "");
				String bytesOrUrl = node.getStringJsonValue(BYTES_OR_URL);
				JSONObject jsonResult = null;
				if(bytesOrUrl.startsWith("http")) {
					jsonResult = OcrUtil.ocrIdentify(ocr, bytesOrUrl);
				}else {
					byte[] bytes = (byte[]) engine.execute(bytesOrUrl, variables);
					jsonResult = OcrUtil.ocrIdentify(ocr, bytes);
				}
				if(jsonResult != null) {
					if(jsonResult.isNull("words_result")) {
						logger.error(jsonResult.toString());
					}else {
						JSONArray wordsResult = jsonResult.getJSONArray("words_result");
						if(wordsResult != null) {
							double average = 0;
							String identifyResult = "";
							for (int i = 0; i < wordsResult.length(); i++) {
								JSONObject probability = wordsResult.getJSONObject(i).getJSONObject("probability");
								if(probability.getDouble("average") > average) {
									average = probability.getDouble("average");
									identifyResult = wordsResult.getJSONObject(i).getString("words");
								}
							}
							variables.put(node.getStringJsonValue(VARIABLE_NAME),identifyResult);
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("ocr操作错误：{}", e);
		}
	}
	
}